package com.xy.p2p.service.impl;


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xy.common.page.Pagination;
import com.xy.common.util.EmailTools;
import com.xy.core.service.impl.BaseServiceImpl;
import com.xy.core.util.BeanUtil;
import com.xy.p2p.dao.TmemberassetaccountDao;
import com.xy.p2p.dao.TmemberassetaccountdetailsDao;
import com.xy.p2p.dao.TtenderrecordDao;
import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tmemberassetaccountdetails;
import com.xy.p2p.model.Ttenderrecord;
import com.xy.p2p.model.Tuser;
import com.xy.p2p.service.TfileaveamessageService;
import com.xy.p2p.service.TfinanceinfoService;
import com.xy.p2p.service.TmemberService;
import com.xy.p2p.service.TmemberassetaccountService;
import com.xy.p2p.service.TmemberassetaccountdetailsService;
import com.xy.p2p.service.TtenderrecordService;

@Service
@Transactional
public class TmemberassetaccountServiceImpl extends BaseServiceImpl<Tmemberassetaccount> implements
		TmemberassetaccountService {
	private TmemberassetaccountDao tmemberassetaccountDao;
	@Autowired
	private TmemberassetaccountdetailsDao tmemberassetaccountdetailsDao;
	@Autowired
	private TtenderrecordDao ttenderrecordDao;
	@Autowired
	private TmemberService tmemberService;
	@Autowired
	private TtenderrecordService ttenderrecordService;
	@Autowired
	private TmemberassetaccountdetailsService tmemberassetaccountdetailsService;
	@Autowired
	private TfinanceinfoService tfinanceinfoService;

	public TmemberassetaccountServiceImpl(TmemberassetaccountDao paramAppRoleDao) {
		super(paramAppRoleDao);
		this.tmemberassetaccountDao = paramAppRoleDao;
	}

	@Override
	public boolean checkExist(String paraName, String paraValue) {
		return tmemberassetaccountDao.checkExist("Tmemberassetaccount", paraName, paraValue);
	}

	@Override
	public List<Tmemberassetaccount> getTmemberassetaccount(Map<String, Object> map) {
		return tmemberassetaccountDao.getTmemberassetaccount(map);
	}
	@Override
	public Pagination getTmemberassetaccountByPage(Map<String, Object> map, int pageNo,
			int pageSize) {
		// TODO Auto-generated method stub
		return tmemberassetaccountDao.getTmemberassetaccountByPage(map, pageNo, pageSize);
	}
	 
   @Override
	public Tmemberassetaccount save(Tmemberassetaccount tmemberassetaccount) {
//		tmemberassetaccount.setModtime(new Date());
		if(tmemberassetaccount.getMaaid()==null){
			//新增
        	return super.save(tmemberassetaccount);
		}else{
			//更新
			Tmemberassetaccount tmemberassetaccount1=tmemberassetaccountDao.get(tmemberassetaccount.getMaaid());
			try {
				BeanUtil.copyNotNullProperties(tmemberassetaccount1, tmemberassetaccount);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			return super.save(tmemberassetaccount1);
		}
	}

   //手工调账
   @Override
	public Tmemberassetaccount ModifyAccount(Tmemberassetaccount tmemberassetaccount, String opr, Tuser tuser, double money, String remark) {
		if ("add".equals(opr)) {
			tmemberassetaccount.setBalance(tmemberassetaccount.getBalance() + money);
			Tmemberassetaccountdetails d = new Tmemberassetaccountdetails(tmemberassetaccount.getTmember(), money, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_IN,
					Tmemberassetaccountdetails.ACCOUNT_CHANGE, new Date(), "平台", "操作人:" + tuser.getUsername() + ";备注内容:" + remark);
			tmemberassetaccountdetailsDao.save(d);
			return super.save(tmemberassetaccount);
		} else if ("sub".equals(opr)) {
			tmemberassetaccount.setBalance(tmemberassetaccount.getBalance() - money);
			Tmemberassetaccountdetails d = new Tmemberassetaccountdetails(tmemberassetaccount.getTmember(), money, Tmemberassetaccountdetails.TMEMBERASSETACCOUNTDETAIL_BORROWING_OUT,
					Tmemberassetaccountdetails.ACCOUNT_CHANGE, new Date(), "平台", "操作人:" + tuser.getUsername() + ";备注:" + remark);
			tmemberassetaccountdetailsDao.save(d);
			return super.save(tmemberassetaccount);
		} else {
			return null;
		}
	}
   //获取总资产(投资资产)
   @Override
   public double getTotalAsset(Tmember tmember){
//	   Map<String,Object> map = new HashMap<String, Object>();
//	   map.put("tmember",tmember);
//	   List<Ttenderrecord> tendList = ttenderrecordDao.getTtenderrecord(map);
//	   map.put("borrowing", 1+"");
//	   map.put("trantype",2+"");
//	   List<Tmemberassetaccountdetails> detailList = tmemberassetaccountdetailsDao.getTmemberassetaccountdetails(map);
//	   double totalT = 0;
//	   double totalD = 0;
//	   for(Ttenderrecord t : tendList){
//		   totalT+=t.getMibmoney();
//	   }
//	   for(Tmemberassetaccountdetails d : detailList){
//		   
//	   }
	   return tmemberassetaccountDao.getTotalAsset(tmember);
   }

	@Override
	public double getTotalBorrow(Tmember tmember) {
		return tmemberassetaccountDao.getTotalBorrow(tmember);
	}

	@Override
	public double getTotalIncome(Tmember tmember) {
		return tmemberassetaccountDao.getTotalIncome(tmember);
	}
   
	/**
	 *电子账单 
	 * */
	public String billing(long memberid){
		//设置两位小数点
	 		DecimalFormat df = new DecimalFormat("0.00");
		Tmember tmember = tmemberService.get(memberid);
		Tmemberassetaccount tmemberassetaccount = new Tmemberassetaccount();
		tmemberassetaccount.setTmember(tmember);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("Tmember", tmember);
		Double assets = this.getTotalAsset(tmember);
		Double borrow = this.getTotalBorrow(tmember);
		Double income = this.getTotalIncome(tmember);
		List<Tmemberassetaccount> list = this.getTmemberassetaccount(queryMap);
		if (list.size() <= 0)
			list.add(tmemberassetaccount);
		// 查询余额贷的收入记录
		List<Ttenderrecord> ttlist = ttenderrecordService.getTtenderrecord(queryMap);
		double yedtotal = 0;
		// 普通投标数
		int nCount = 0;
		// 普通投标利率和
		double npa = 0;
		// 余额贷投标数
		int yednCount = 0;
		// 余额贷投标利率和
		double yednpa = 0;
		for (Ttenderrecord t : ttlist) {
			if (8 == t.getTfinanceinfo().getTargettype()) {
				yedtotal += t.getMibmoney();
				yednCount++;
				yednpa += t.getFinancepa();
			} else {
				nCount++;
				npa += t.getFinancepa();
			}
		}
		List<Tmemberassetaccountdetails> tt = tmemberassetaccountdetailsService.getTmemberassetaccountdetails(queryMap);
		double yedincome = 0;
		for (Tmemberassetaccountdetails t : tt) {
			if (1 == t.getBorrowing() && 28 == t.getTrantype()) {
				yedincome += t.getTranamount();
			}
		}
		// 普通标平均利率和投标总数
		if (npa == 0 || nCount == 0)
			npa = 0;
		else
			npa = npa / nCount * 100;
		// 余额贷平均利率和投标总数
		if (yednpa == 0 || yednCount == 0)
			yednpa = 0;
		else
			yednpa = yednpa / yednCount * 100;
		Double principal = 0.0;
		Double interest = 0.0;
		Double fee = 0.0;
		int number = 0;
		queryMap.put("status", 7);
		for (Tfinanceinfo t : tfinanceinfoService.getTfinanceinfo(queryMap)) {
			if (t.getTargettype() != 8) {
				principal += t.getSubpri();
				interest += t.getAlino();
				fee += t.getMftba();
				++number;
			}
		}
		Double money = assets + list.get(0).getBalance() + list.get(0).getAmountfrozen() - borrow;
		String Money = "";
		String Balance = "";
		String Dong = "";
		if(money<0)
			Money = "-&#165;" + df.format(Math.abs(money));
		else
			Money = "&#165;" + df.format(money);
		if(list.get(0).getBalance()<0)
			Balance = "-&#165;" + df.format(Math.abs(list.get(0).getBalance()));
		else
			Balance = "&#165;" + df.format(list.get(0).getBalance());
		if(list.get(0).getAmountfrozen()<0)
			Dong = "-&#165;" + df.format(list.get(0).getAmountfrozen());
		else
			Dong = "&#165;" + df.format(list.get(0).getAmountfrozen());
		SimpleDateFormat dd = new SimpleDateFormat("yyyy年MM月dd日");
		String email = tmember.getEmail();
		String tile = "贷一贷电子账单";
		String name = tmember.getTruename();
		if(null==name){
			name = "（你还没有填写真实姓名，请登录后填写）";
		}
		//发送内容
		StringBuffer str = new StringBuffer();
		str.append("<div style='margin:0px auto; width:800px; color:#999; background-color:#FFFFFF; padding-top:10px; padding-bottom:20px;' >	<div style='width:760px; text-align:center; font-size:30px; color:#ff9a00; font-weight:bold;'>贷一贷电子账单</div>    <div style='width:760px; text-align:center; font-size:20px;'>账单日：");
		str.append(dd.format(new Date()));
		str.append("</div>    <div>尊敬的");
		str.append(name);
		str.append("，您好！</div>    <div>&nbsp;&nbsp;&nbsp;&nbsp;感谢您选择贷一贷平台进行资金筹借和理财增值，以下是您的个人账户电子账单：</div>");
		str.append("<div style='margin:0px auto; width:760px; padding-top:15px;'>    	<div style='width:760px;background-color:rgb(255, 255, 213);'>        	<span style='display:inline-block; width:147px; text-align:center; font-size:18px;'>账户总资产</span>            <span style='display:inline-block; width:147px; text-align:center; font-size:18px;'>投资资产</span>            <span style='display:inline-block; width:147px; text-align:center; font-size:18px;'>融资负债</span>            <span style='display:inline-block; width:147px; text-align:center; font-size:18px;'>可用金额</span>            <span style='display:inline-block; width:140px; text-align:center; font-size:18px;'>冻结金额</span>        </div>        <div style='width:760px; margin:5px 0px; padding-bottom:40px; border-bottom:1px solid #CCC;'>        	<ul style='margin:0px; padding:0px;'>            	<li style='list-style:none;width:132px; height:30px; line-height:30px; float:left; text-align:center;' >");
		str.append(Money);
		str.append("元                </li>                <li style='list-style:none;height:30px; line-height:30px; float:left; margin:0px 5px;'>=</li>                <li style='list-style:none;width:132px; height:30px; line-height:30px; float:left; text-align:center;' >&#165;");
		str.append(df.format(assets));
		str.append("元                </li>                <li style='list-style:none;height:30px; line-height:30px; float:left; margin:0px 5px;'>+</li>                <li style='list-style:none;width:132px; height:30px; line-height:30px; float:left; text-align:center;color:#F00;' >-&#165;");
		str.append(df.format(borrow));
		str.append("元                </li>                <li style='list-style:none;height:30px; line-height:30px; float:left; margin:0px 5px;'>+</li>                <li style='list-style:none;width:132px; height:30px; line-height:30px; float:left; text-align:center;' >");
		str.append(Balance);
		str.append("元                </li>                <li style='list-style:none;height:30px; line-height:30px; float:left; margin:0px 5px;'>+</li>                <li style='list-style:none;width:125px; height:30px; line-height:30px; float:left; text-align:center;'>");
		str.append(Dong);
		str.append("元                </li>                <li style='clear:both;list-style:none;'></li>            </ul>        </div>        <div style='width:760px; font-size:18px; margin-bottom:15px; margin-top:15px;'>            <span style='color:#ff9a00; margin-right:30px;'>投资账户</span>            <span style='display:inline-block;'>已赚总金额<span style='color: rgb(218, 139, 21);'>&#165;");
		str.append(df.format(income));
		str.append("元</span></span>        </div>        <div style='width:760px; background-color:rgb(255, 255, 213); border-bottom:1px solid #CCC;' >            <span style='display:inline-block;width:128px; text-align:center; font-size:18px;'>投资方式</span>            <span style='display:inline-block;width:150px; text-align:center; font-size:18px;'>账户资产</span>            <span style='display:inline-block;width:150px; text-align:center; font-size:18px;'>已赚金额</span>            <span style='display:inline-block;width:145px; text-align:center; font-size:18px;'>加权平均收益率</span>            <span style='display:inline-block;width:140px; text-align:center; font-size:18px;'>持有数量</span>        </div>        <div style='width:760px; padding-bottom:25px; padding-top:5px; border-bottom:1px solid #CCC;'>        	<ul style='margin:0px; padding:0px;'>            	<li style='list-style:none;width:128px; float:left;  text-align:center; margin-right:5px;' >投资标的</li>                <li style='list-style:none;width:150px;text-align:center;float:left; margin-right:5px;' >&#165;");
		str.append(df.format(assets));
		str.append("元</li>                <li style='list-style:none;width:150px; text-align:center;float:left; margin-right:25px;' >&#165;");
		str.append(df.format(income));
		str.append("元</li>                <li style='list-style:none;width:110px; text-align:center;float:left; margin-right:52px;' >&#165;");
		str.append(df.format(npa));
		str.append("%</li>                <li style='list-style:none;width:90px; text-align:center;float:left; margin-right:5px;' >");
		str.append(nCount);
		str.append("</li>                <li style='clear:both;text-align:center;list-style:none'></li>            </ul>                    </div>        <div style='width:760px; padding-bottom:25px; padding-top:5px; border-bottom:1px solid #CCC;'>       		 <ul style='margin:0px; padding:0px;'>            	<li style='list-style:none;width:128px;float:left; text-align:center; margin-right:5px;'>余额贷</li>                <li style='list-style:none;width:150px; text-align:center;float:left; margin-right:5px;'>&#165;");
		str.append(df.format(yedtotal));
		str.append("元</li>                <li style='list-style:none;width:150px;text-align:center;float:left; margin-right:25px;'>&#165;");
		str.append(df.format(yedincome));
		str.append("元</li>                <li style='list-style:none;width:110px;text-align:center;float:left; margin-right:52px;'>&#165;");
		str.append(df.format(yednpa));
		str.append("%</li>                <li style='list-style:none;width:90px;text-align:center;float:left;margin-right:5px;'>");
		str.append(yednCount);
		str.append("</li>                <li style='clear:both;list-style:none'></li>            </ul>        </div>");
		str.append("<div style='width:760px; background-color:rgb(255, 255, 213); border-bottom:1px solid #CCC;' >            <span style='display:inline-block;width:128px; text-align:center; font-size:18px;'>借款数量</span>            <span style='display:inline-block;width:150px; text-align:center; font-size:18px;'>下期待还本金</span>            <span style='display:inline-block;width:150px; text-align:center; font-size:18px;'>下期待还利息</span>            <span style='display:inline-block;width:145px; text-align:center; font-size:18px;'>管理费</span>            <span style='display:inline-block;width:140px; text-align:center; font-size:18px;'>逾期费用</span>        </div>");
		str.append("<div style='width:760px; padding-bottom:25px; padding-top:5px; border-bottom:1px solid #CCC;'>       		 <ul style='margin:0px; padding:0px;'>            	<li style='list-style:none;width:128px;float:left; text-align:center; margin-right:5px;'>");
		str.append(number);
		str.append("</li>                <li style='list-style:none;width:150px; text-align:center;float:left; margin-right:5px;'>&#165;");
		str.append(df.format(principal));
		str.append("元</li>                <li style='list-style:none;width:150px;text-align:center;float:left; margin-right:25px;'>&#165;");
		str.append(df.format(interest));
		str.append("元</li>                <li style='list-style:none;width:110px;text-align:center;float:left; margin-right:52px;'>&#165;");
		str.append(df.format(fee));
		str.append("元</li>                <li style='list-style:none;width:90px; text-align:center;float:left;margin-right:5px;'>&#165;0.00元</li>                <li style='clear:both;list-style:none'></li>            </ul>");
		str.append("</div>※如您对账单有任何疑问，请致电客服热线400-1122-363，我们将竭诚为您服务！<br>※更多细节您可以登录www.51d1d.com&nbsp;进入&nbsp;我的账户&nbsp;中进行查看 。<br>※关于提现的温馨提示：提现账户须为用户名本人的银行账户，并请在提现时准确填写您的开户行。</div></div>");
		String content = str.toString();
		try {
			//发送邮件
			EmailTools.sendHtmlEmail(content, tile, email);
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
		return "test.html";
	}

}